<?php
include('database.php');
include('auth.php');
include('core.php');

/**
  JSON and HTML Ajax functions
*/


/**
 Checks user permission
*/
function check_permission($auth_level)
{
    if (!$_SESSION[site_id] || $_SESSION[site_id]['permission'] < $auth_level)
    {
        header('Content-type: application/json');
        die( json_encode( array( "option" => $_GET['option'], 
                                 "response" => "forbidden") ));
    }
}

/**
 Checks if employee time card is conflicting with another.
*/
function time_card_check($employee_id, $date, $intime, $outtime)
{
    check_permission(3);

    $fdate = date("Y-m-d", strtotime($date));
    $conflicting = query_fetch("SELECT reports.id from reports, clocks WHERE " . 
                               "clocks.report_id = reports.id AND " . 
                               "clocks.employee_id=$employee_id AND " .
                               "reports.reportdate = '$fdate' AND " .
                               "'{$intime}00' < clocks.outtime AND clocks.intime < '{$outtime}00' LIMIT 1");

    header('Content-type: application/json');
    $return = array("option" => $_GET['option'],
                    "employee" => $employee_id,
                    "date" => $fdate, "intime"=> $intime, "outtime"=>$outtime);

    if ($conflicting)
    {
        $return["response"] = "conflicting";
        $return["conflicting"] = $conflicting["id"];
    }
    else
    {
        $return["response"] = "ok";
    }
    die( json_encode($return) );
}

/**
    Checks if username is avaliable
*/
function username_avaliable($username)
{
    check_permission(3);

    $employee = query_fetch("SELECT id FROM employees WHERE USERNAME='$username' LIMIT 1");

    header('Content-type: application/json');
    die( json_encode(
                     array("option" => $_GET['option'],
                           "username" => $username,
                           "response" => ($employee? "unavaliable" : "avaliable")) ));

}



/**
 Select correct option based on get url parameters
*/
switch ($_GET["option"])
{
    case "timecardcheck":

        time_card_check(mysql_real_escape_string($_GET["employee"]), 
                        mysql_real_escape_string($_GET["date"]),
                        mysql_real_escape_string($_GET["intime"]),
                        mysql_real_escape_string($_GET["outtime"]));
        break;

    case "username":
        username_avaliable(mysql_real_escape_string($_GET["username"]));
        break;

    default:

    header('Content-type: application/json');
    die( json_encode(
                     array("option" => $_GET['option'],
                           "response" => "invalid") ));             
}

?>
